package com.openapi.protocol.decode.subPackageHandle.driverContrastResult;

import com.openapi.data.JT808PackageData;
import com.openapi.data.JT808PushData;
import com.openapi.protocol.decode.subPackageHandle.SubPackageHandle;
import com.openapi.protocol.decode.subPackageHandle.SubPackageStatus;

import com.openapi.protocol.encode.PackageQingdao;
import exsun.jt808.data.config.jt808.Jt808DistributeMsgTopic;

import exsun.jt808.data.distribute_data.Qingdao.DriverContrastResultResponse;
import exsun.jt808.data.parseUtil.GpsUtil;
import exsun.jt808.data.upload_data.Qingdao.DriverContrastResult;
import exsun.jt808.data.util.parse.DecoderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 驾驶员对比结果上报解析
 */
@Component
public class DriverContrastResultHandle extends SubPackageHandle {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public  String getPakKey(JT808PackageData data) {
        return data.dvo +"_"+ data.msgSerialNo;
    }


    /**
     * 驾驶员对比结果上报
     */
    @Override
    public DriverContrastResult parse(JT808PackageData data, byte[] totalBodys) {
        DriverContrastResult obj = new DriverContrastResult();
        super.setResultObj(obj,data,Jt808DistributeMsgTopic.DriverContrastResult_upload);
        obj.setResult(DecoderUtils.parseIntFromBytes(totalBodys,0,1));
        obj.setContrastSimilarityValue(DecoderUtils.parseIntFromBytes(totalBodys,1,1));
        obj.setContrastSimilarity(DecoderUtils.parseIntFromBytes(totalBodys,2,2));
        obj.setContrastType(DecoderUtils.parseIntFromBytes(totalBodys,4,1));
        int driverIdLength = DecoderUtils.parseIntFromBytes(totalBodys,5,1);
        obj.setDriverId(DecoderUtils.parseStringFromBytes(totalBodys,6,driverIdLength));
        int facePictureIdLength = DecoderUtils.parseIntFromBytes(totalBodys,6+driverIdLength,1);
        obj.setFacePictureId(DecoderUtils.parseBcdStringFromBytes(totalBodys,7+driverIdLength,facePictureIdLength));
        obj.setPositionMsg(GpsUtil.parseGps(DecoderUtils.byteCopy(totalBodys,7+driverIdLength+facePictureIdLength,28),false));
        obj.setPictureFormat(DecoderUtils.parseIntFromBytes(totalBodys,35+driverIdLength+facePictureIdLength,1));

        if (obj.getResult() == 0 || obj.getResult() == 1){
            obj.setPicturePackage(DecoderUtils.byteCopy(totalBodys,36+driverIdLength+facePictureIdLength,totalBodys.length-(36+driverIdLength+facePictureIdLength)));
        }
        return obj;
    }

    /**
     * 驾驶员对比结果上报应答
     */
    private List<JT808PushData> rsp(JT808PackageData data){
        List<JT808PushData> list = new ArrayList<>();
        List<Integer> miss = super.getMissItems(data);
        JT808PackageData firstPak = super.getPakage(data, 1);
        if(firstPak==null)return list;
        int orgSerialNum = DecoderUtils.parseIntFromBytes(firstPak.getBodyBuffers(), 0, 4);
        DriverContrastResultResponse rep = new DriverContrastResultResponse(orgSerialNum, miss);
        JT808PushData body = PackageQingdao.driverContrastResultResponse(rep);
        list.add(body);
        return list;
    }

    public List<JT808PushData> decode(JT808PackageData data){
        logger.info("接收多媒体数据：{}，{}，{}，{}",data.dvo, data.packageIndex, data.packageSize,data.msgSerialNo);
        List<JT808PushData> list =  new ArrayList<>();
        try {
            SubPackageStatus status = super.append(data);
            String key = getPakKey(data);
            // 检查缺失项，无缺失项,处理数据:存储、推送、应答
            if(status == SubPackageStatus.complete){
                //图片数据上传【完成】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
                byte[] totalBytes = super.getAllData(data);
                finished(data,  totalBytes);
                super.remove(key);
            }
            if(status == SubPackageStatus.receiving){
                //图片数据上传【通用】应答
                list.add(super.Response(data));
            }
            if(status == SubPackageStatus.missing){
                //图片数据上传【缺失】应答
                List<JT808PushData> bodys = rsp(data);
                list.addAll(bodys);
            }
            return list;
        }catch (Exception e){
            logger.error("图片数据解析异常：{}"+e.getMessage());
        }
        return list;
    }

    private void finished(JT808PackageData data, byte[] totalBytes) throws Exception{
        //存储到ftp服务器
        DriverContrastResult sendData = parse(data, totalBytes);
        String filePath = DriverContrastPictureHandle.getFilePath(sendData.dvo);
        String fileName = DriverContrastPictureHandle.getFileName(sendData.getPictureFormat());
        String path = "ftp://" + jt808ServerConfig.getJt808FtpServer() + ":" + jt808ServerConfig.getJt808FtpPort() +  filePath + "/" + fileName;
        logger.info("比对人脸图片存储至ftp...  {}", path);
        boolean result = DriverContrastPictureHandle.saveToFTP(super.jt808ServerConfig, fileName, filePath, sendData.getPicturePackage());
        logger.info("比对人脸图片存储" + (result == true?"成功:":"失败:") + path);
        //推送数据
        super.kafkaService.push(sendData);
    }
}
